package com.example.mydianping.service.impl;

import com.example.mydianping.dto.Result;
import com.example.mydianping.dto.UserDTO;
import com.example.mydianping.mapper.VoucherOrderMapper;
import com.example.mydianping.mapper.VoucherSeckillMapper;
import com.example.mydianping.pojo.SeckillVoucher;
import com.example.mydianping.pojo.VoucherOrder;
import com.example.mydianping.service.VoucherOrderService;
import com.example.mydianping.utils.CreateOnlyId;
import com.example.mydianping.utils.RedisLock;
import com.example.mydianping.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class VoucherOrderServiceImpl implements VoucherOrderService {
    @Resource
    private VoucherSeckillMapper voucherSeckillMapper;
    //id 生成器
    @Resource
    private CreateOnlyId createOnlyId;
    @Resource
    private VoucherOrderMapper voucherOrderMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override

    public Result seckillVoucher(Long voucherId) {
        //查询秒杀优惠卷
        SeckillVoucher seckillVoucher = voucherSeckillMapper.selectById(voucherId);
        //判断是否在活动时间内
        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("活动尚未开始");
        }
        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("活动已经结束");
        }
        //先判断一人一单逻辑
        UserDTO user = UserHolder.getUser();
        RedisLock redisLock = new RedisLock("order:"+user.getId(),stringRedisTemplate);
        boolean getLock = redisLock.tryLock();//尝试获取锁
        if(!getLock){
            //获取锁失败，直接返回失败
            return Result.fail("一个用户只能购买一单");
        }
        //获取锁成功
        long orderKey = 0;
        try {
            //查询当前店铺下的卷是否已经有 user_id 了，有就返回fail
            int count = voucherOrderMapper.overBuy(user.getId(), voucherId);
            if(count > 0){
                return Result.fail("一个用户只能购买一单");
            }
            //查看库存
            if(seckillVoucher.getStock() < 1){
                return Result.fail("库存不足");
            }
            //扣减库存
            boolean flag = voucherSeckillMapper.updateSecStock(voucherId);
            if(!flag){
                return Result.fail("库存不足");
            }
            //创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            orderKey = createOnlyId.createID("order");
            voucherOrder.setId(orderKey);
            voucherOrder.setVoucherId(voucherId);
            voucherOrder.setUserId(user.getId());
            //将订单存入数据库
            voucherOrderMapper.insert(voucherOrder);
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            //释放锁
            redisLock.unLock();
        }
        return Result.ok(orderKey);
    }
}
